#include "TestEngine.h"
#include <cstddef>
#include <cstdint>
#include <memory>
#include "DateTime.h"
#include "Logger.h"
#include "OnTestMsg.h"

using namespace std::placeholders;
using namespace xncc::user;
using namespace xncc::types;
TestEngine::TestEngine() : EventEngine(10) {}

void TestEngine::init()
{
    auto testFunc = std::bind(&TestEngine::handleTestMsg, this, _1, _2, _3, _4);
    registerUserFunc(1000, testFunc);
}

void TestEngine::handleConnected(connection_id_t msg, thread_id_t tid)
{
    LOG_INFO(CONSOLE_LOG) << "TestEngine receive conn msg  peer addr = " << getPeerAddr(msg);
    auto timerId = setTimerFunc(DateTime::timeMicro(), 1000, std::bind(&TestEngine::handleSendTestMsg, this, tid, msg));
    //  handleSendTestMsg(tid, fd);
    timerIds_[msg] = timerId;
}

void TestEngine::handleSendTestMsg(thread_id_t tid, connection_id_t connId)
{
    auto       rsp = std::make_shared<OnTestMsg>();
    static int num = 1;
    rsp->init(num++);
    sendData(rsp->data_, static_cast<uint32_t>(strlen(rsp->data_)), 1000, tid, connId);
}

void TestEngine::handleTestMsg(const char* buf, uint32_t len, thread_id_t tid, connection_id_t connId)
{
    std::string rsp(buf, static_cast<std::size_t>(len));

    LOG_INFO(CONSOLE_LOG) << "receive client rsp = " << rsp;
    if (rsp == "2000") {
        kickConnection(connId, tid);
        cancelTimer(timerIds_[connId]);
    }
}

void TestEngine::handleDisconnected(connection_id_t msg, thread_id_t tid, const std::string& disconnectedReason)
{
    LOG_INFO(CONSOLE_LOG) << "TestEngine receive dis conn msg  peer addr = " << getPeerAddr(msg)
                          << " reason = " << disconnectedReason;
    cancelTimer(timerIds_[msg]);
}